using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SheLife.Application.Interfaces;
using System;
using System.Threading.Tasks;

namespace SheLife.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class MqttController : ControllerBase
    {
        private readonly IMqttService _mqttService;
        private readonly IMqttPublishService _mqttPublishService;

        public MqttController(IMqttService mqttService, IMqttPublishService mqttPublishService)
        {
            _mqttService = mqttService;
            _mqttPublishService = mqttPublishService;
        }

        [HttpPost("connect")]
        public async Task<IActionResult> Connect()
        {
            try
            {
                await _mqttService.ConnectAsync();
                return Ok(new { message = "MQTT连接成功" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = $"MQTT连接失败: {ex.Message}" });
            }
        }

        [HttpPost("disconnect")]
        public async Task<IActionResult> Disconnect()
        {
            try
            {
                await _mqttService.DisconnectAsync();
                return Ok(new { message = "MQTT断开连接成功" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = $"MQTT断开连接失败: {ex.Message}" });
            }
        }

        [HttpPost("publish")]
        public async Task<IActionResult> Publish([FromBody] MqttPublishRequest request)
        {
            try
            {
                await _mqttService.PublishAsync(request.Topic, request.Message, request.QosLevel);
                return Ok(new { message = "MQTT消息发布成功" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = $"MQTT消息发布失败: {ex.Message}" });
            }
        }

        [HttpPost("subscribe")]
        public async Task<IActionResult> Subscribe([FromBody] MqttSubscribeRequest request)
        {
            try
            {
                await _mqttService.SubscribeAsync(request.Topic, request.QosLevel);
                return Ok(new { message = "MQTT订阅成功" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = $"MQTT订阅失败: {ex.Message}" });
            }
        }

        [HttpPost("unsubscribe")]
        public async Task<IActionResult> Unsubscribe([FromBody] MqttUnsubscribeRequest request)
        {
            try
            {
                await _mqttService.UnsubscribeAsync(request.Topic);
                return Ok(new { message = "MQTT取消订阅成功" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = $"MQTT取消订阅失败: {ex.Message}" });
            }
        }

        [HttpPost("publish/cycle-update")]
        public async Task<IActionResult> PublishCycleUpdate([FromBody] MqttCycleUpdateRequest request)
        {
            try
            {
                await _mqttPublishService.PublishCycleUpdateAsync(
                    request.UserId, 
                    request.StartDate, 
                    request.EndDate, 
                    request.CycleLength,
                    request.PeriodLength);
                return Ok(new { message = "生理周期更新消息发布成功" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = $"生理周期更新消息发布失败: {ex.Message}" });
            }
        }

        [HttpPost("publish/symptom-record")]
        public async Task<IActionResult> PublishSymptomRecord([FromBody] MqttSymptomRecordRequest request)
        {
            try
            {
                await _mqttPublishService.PublishSymptomRecordAsync(
                    request.UserId, 
                    request.SymptomType, 
                    request.Severity, 
                    request.RecordDate);
                return Ok(new { message = "症状记录消息发布成功" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = $"症状记录消息发布失败: {ex.Message}" });
            }
        }

        [HttpPost("publish/temperature-record")]
        public async Task<IActionResult> PublishTemperatureRecord([FromBody] MqttTemperatureRecordRequest request)
        {
            try
            {
                await _mqttPublishService.PublishTemperatureRecordAsync(
                    request.UserId, 
                    request.Temperature, 
                    request.RecordDate);
                return Ok(new { message = "基础体温记录消息发布成功" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = $"基础体温记录消息发布失败: {ex.Message}" });
            }
        }

        [HttpPost("publish/ovulation-prediction")]
        public async Task<IActionResult> PublishOvulationPrediction([FromBody] MqttOvulationPredictionRequest request)
        {
            try
            {
                await _mqttPublishService.PublishOvulationPredictionAsync(
                    request.UserId, 
                    request.OvulationDate, 
                    request.FertilityWindowStart, 
                    request.FertilityWindowEnd);
                return Ok(new { message = "排卵期预测消息发布成功" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = $"排卵期预测消息发布失败: {ex.Message}" });
            }
        }

        [HttpPost("publish/health-reminder")]
        public async Task<IActionResult> PublishHealthReminder([FromBody] MqttHealthReminderRequest request)
        {
            try
            {
                await _mqttPublishService.PublishHealthReminderAsync(
                    request.UserId, 
                    request.ReminderType, 
                    request.Title, 
                    request.Message, 
                    request.ReminderDate);
                return Ok(new { message = "健康提醒消息发布成功" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = $"健康提醒消息发布失败: {ex.Message}" });
            }
        }
    }

    public class MqttPublishRequest
    {
        public string Topic { get; set; }
        public string Message { get; set; }
        public int QosLevel { get; set; } = 1;
    }

    public class MqttSubscribeRequest
    {
        public string Topic { get; set; }
        public int QosLevel { get; set; } = 1;
    }

    public class MqttUnsubscribeRequest
    {
        public string Topic { get; set; }
    }

    public class MqttCycleUpdateRequest
    {
        public Guid UserId { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        public int CycleLength { get; set; }
        public int PeriodLength { get; set; }
    }

    public class MqttSymptomRecordRequest
    {
        public Guid UserId { get; set; }
        public string SymptomType { get; set; }
        public int Severity { get; set; }
        public DateTime RecordDate { get; set; }
    }

    public class MqttTemperatureRecordRequest
    {
        public Guid UserId { get; set; }
        public decimal Temperature { get; set; }
        public DateTime RecordDate { get; set; }
    }

    public class MqttOvulationPredictionRequest
    {
        public Guid UserId { get; set; }
        public DateTime OvulationDate { get; set; }
        public DateTime FertilityWindowStart { get; set; }
        public DateTime FertilityWindowEnd { get; set; }
    }

    public class MqttHealthReminderRequest
    {
        public Guid UserId { get; set; }
        public string ReminderType { get; set; }
        public string Title { get; set; }
        public string Message { get; set; }
        public DateTime ReminderDate { get; set; }
    }
}